package com.dcits.selenium;

import java.lang.reflect.Constructor;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebElement;
import org.testng.log4testng.Logger;

import com.dcits.MainTest;
import com.dcits.util.prop.Prop;
import com.dcits.util.prop.PropKit;

/**
 * 测试元素,获取通过配置文件管理的元素对象
 * @author xuwangcheng
 * @version 2018.3.22
 *
 */
public class TestElement {
	private static final Logger logger = Logger.getLogger(TestElement.class);
	/**元素对象管理的配置文件*/
	public static final Prop elementProp = PropKit.use("com//dcits//config" + MainTest.dev_name + "//elementLocation.properties");
	private WebElement webElement;
	
	public TestElement(WebElement element) {
		// TODO Auto-generated constructor stub
		this.webElement = element;
	}
	
	public TestElement getElement(String elementKey) throws Exception {
		return getElement(elementKey, this.getWebElement());
	}
	
	public WebElement getWebElement(String elementKey) throws Exception  {
		return getElement(elementKey).getWebElement();
	}
	
	/**
	 * 通过key值获取TestElement对象
	 * @param elementKey
	 * @param driver
	 * @return
	 * @throws Exception
	 */
	public static TestElement getElement(String elementKey, SearchContext driver) throws Exception {
		By by = getBy(elementKey);
		if (by != null) {
			String[] keys = elementProp.get(elementKey).split("\\s+");
			if (keys.length == 2) {
				return new TestElement(by.findElement(driver));
			}

			List<WebElement> els = by.findElements(driver);
			return new TestElement(els.get(Integer.valueOf(keys[2]) - 1));
		}
		return null;
		
		
	}
	
	/**
	 * 同key值获取查询条件By
	 * @param elementKey
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static By getBy (String elementKey) throws Exception {
		String key = elementProp.get(elementKey);
		if (StringUtils.isBlank(key)) {
			throw new Exception("匹配不到key值为" + elementKey + "的元素对象信息!");
		}
		String[] keys = key.split("\\s+");
		try {
			Class clz = Class.forName("org.openqa.selenium.By$By" + keys[0]);
			Constructor ctr = clz.getConstructor(String.class);
			return (By) ctr.newInstance(keys[1]);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("创建By实例失败：" + key, e);
			throw e;
		}
	}
	
	public void setWebElement(WebElement webElement) {
		this.webElement = webElement;
	}
	
	public WebElement getWebElement() {
		return webElement;
	}
}
